<?php

namespace app\common\service\UserService;

use app\Normal;
use app\model\BbcModel\Manager;
use app\model\BbcModel\AuthGroup;
use app\model\BbcModel\AuthNode;
use app\model\BbcModel\ManagerLog;
use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Channel;

/**
 * 用户信息管理中心 
 * @author Administrator
 */
class UserManageService
{
    const master_system_user_key = 'master_user_info';
    const master_login_cache_key = 'master_login_key_';
    const master_login_expire_time = 86400;
    
     /**
     * user login encrypt iv
     * @access private
     * @var    string
     */
    private static $userLoginEncryptIv = 'usersAutoLoginIv';
    
    /**
     * user login token salt
     * @access private
     * @var    string
     */
    private static $userTokenSalt = 'userTokenSalt';
    
    /**
     * 系统管理员登录
     * @param array $param
     * $param['account'] = "xiaochen"
     * $param['password'] = "123456"
     */
    public function userLogin( array $param )
    {
        if (empty($param['account'])) {
            return Normal::returnCode(Normal::FAIL, '账号不能为空');
        }
        
        if (empty($param['password'])) {
            return Normal::returnCode(Normal::FAIL, '密码不能为空');
        }
        //验证账号信息
        $manager = Manager::instance()->info(['account' => trim($param['account'])]);
        if (empty($manager)) {
            return Normal::returnCode(Normal::FAIL, '账号不存在');
        }
        
        if ($manager['status'] != 1) {
            return Normal::returnCode(Normal::FAIL, '账号被冻结');
        }
        
        if ($manager['password'] != md5($param['password']) && $manager['password'] != $param['password']) {
            return Normal::returnCode(Normal::FAIL, '密码错误');
        }
        if($manager['cb_id']>0){
            $cb= ChannelBusiness::instance()->info(['id'=>$manager['cb_id']]);
            if($cb&&$cb['status']==0){
                return Normal::returnCode(Normal::FAIL, '该渠道商已经被禁用');
            }
        }
        $channel= Channel::instance()->info(['id'=>$manager['cid']]);
        if($channel&&$channel['status']==0){
            return Normal::returnCode(Normal::FAIL, '该渠道已经被禁用');
        }
        $encrypt_str=$manager['id'].'&'.$manager['cid'].'&'.$manager['cb_id'].'&'.$manager['group_id'].'&'.time();
        $token= $this->keyEncrypt($encrypt_str);
        $redis = getRedisObj();
        $redis->set(self::master_login_cache_key.$manager['id'],$token, self::master_login_expire_time);
        return Normal::returnCode(Normal::SUC,"登录成功",[
//            "account"   => $manager['account'],
//            "name"      => $manager['name'],
//            "manager_id"        => $manager['id'],
//            "cid"       => $manager['cid'],
//            "cb_id"     => $manager['cb_id'],
//            "group_id"  => $manager['group_id'],
            'token'     =>$token
        ]);
    }
    
    /**
     * 登出
     * @param array $param
     * @return array
     */
    public function userLogout(array $param):array {
        $redis = getRedisObj();
        $redis->set(self::master_login_cache_key.$param['manager_id'],'', self::master_login_expire_time);
        return Normal::returnCode(Normal::SUC,"登出成功");
    }

    /**
     * 系统管理员登录
     * @param array $param
     * $param['account'] = "xiaochen"
     * $param['password'] = "123456"
     */
    public function userRegister( array $param )
    {
        return Normal::returnCode(Normal::SUC,"注册成功");
    }    
    
    /**
     * 获取当前系统用户登录的角色权限信息
     * @param int $manager_id
     */
    public function getSystemLoginUserInfoByUserID( int $manager_id ) 
    {
        if (empty($manager_id)) {
            return Normal::returnCode(Normal::FAIL,"manager_id必传");
        }
        $manager= Manager::instance()->info(['id'=>$manager_id]);
        if(empty($manager)){
            return Normal::returnCode(Normal::FAIL,"管理员信息不存在");
        }
        $param=[
            "cid"       => $manager['cid'],
            "cb_id"     => $manager['cb_id'],
            "group_id"  => $manager['group_id'],
        ];
        $authresult= $this->getAuth($param);
        if($authresult['code']!= Normal::SUC){
            return $authresult;
        }
        $data=[
            "account"   => $manager['account'],
            "name"      => $manager['name']
        ];
        $data= array_merge($data,$authresult['data']);
        return Normal::returnCode(Normal::SUC,"获取成功",$data);
    }
    /**
     * 加密key
     * @param  string $encrypt_str
     * @access private
     * @return string
     */
    public  function keyEncrypt(string $encrypt_str):string
    {
        return openssl_encrypt($encrypt_str, 'AES-256-CBC', self::$userTokenSalt, 0, self::$userLoginEncryptIv);
    }
    
    /**
     * 解密key
     * @param  string $decrypt_str
     * @access private
     * @return string
     */
    public  function keyDecrypt(string $decrypt_str):string
    {
        return openssl_decrypt($decrypt_str, 'AES-256-CBC', self::$userTokenSalt, 0, self::$userLoginEncryptIv);
    }
    
    
    /**
     * 获取管理员列表分页
     * @param array $param
     * @return array
     */
    public function getManagerListByPage(array $param):array
    {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:20;
        $where=[];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }else{
            $where[] = ['cb_id', '=', 0];
        }
        if (!empty($param['account'])) {
            $where[] = ['account', 'like', '%'.$param['account'].'%'];
        }
        if (!empty($param['name'])) {
            $where[] = ['name', 'like', '%'.$param['name'].'%'];
        }
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['status', '=', $param['status']];
        }
        if (!empty($param['cd_start'])) {
            $where[] = ['cd', '>=', strtotime($param['cd_start'])];
        }
        if (!empty($param['cd_end'])) {
            $where[] = ['cd', '<=', strtotime($param['cd_end'])];
        }
        $data= Manager::instance()->listPages($where, $limit, $page);
        $count=Manager::instance()->countNum($where);
        $auth_group = AuthGroup::instance()->lists(['status' => 1,'cid'=>$param['cid'], '_fields_' => ['id', 'name']]);
        $auth_group = array_column($auth_group, null,'id');
        $mids=array_column($data,'mid');
        if( !empty($mids) ) {
            $Members = callTcpService('bbcUserAccountsByMids',['mids'=>$mids]);
            if($Members['code']==200){
                $memberlists=array_column($Members['data'], 'mobile','mid');
            }else{
                return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$Members['msg']);
            }
            foreach ($data as &$item) {
                unset($item['password']);
                $item['statusname'] = Manager::instance()->status[$item['status']];
                $item['group']  = !empty($auth_group[$item['group_id']]) ? $auth_group[$item['group_id']]['name'] : '';
                $item['mobile']  = $memberlists[$item['mid']];
                unset($item);
            }
            return Normal::returnCode(Normal::SUC,"获取成功",['list'=>$data,'total'=>$count]);
        } else {
            return Normal::returnCode(Normal::SUC,"获取成功",['list'=>[],'total'=>0]);
        }
    }
    /**
     * 获取管理员列表
     * @param array $param
     * @return array
     */
    public function getManagerList(array $param):array
    {
        $page=$param['page']??1;
        $limit=$param['limit']??20;
        $where=[];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }else{
            $where[] = ['cb_id', '=', 0];
        }
        if (!empty($param['account'])) {
            $where[] = ['account', 'like', '%'.$param['account'].'%'];
        }
        if (!empty($param['name'])) {
            $where[] = ['name', 'like', '%'.$param['name'].'%'];
        }
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['status', '=', $param['status']];
        }
        if (!empty($param['cd_start'])) {
            $where[] = ['cd', '>=', strtotime($param['cd_start'])];
        }
        if (!empty($param['cd_end'])) {
            $where[] = ['cd', '<=', strtotime($param['cd_end'])];
        }
        $data= Manager::instance()->Lists($where);
        $auth_group = AuthGroup::instance()->lists(['status' => 1,'cid'=>$param['cid'], '_fields_' => ['id', 'name']]);
        $auth_group = array_column($auth_group, null,'id');
        foreach ($data as &$item) {
            unset($item['password']);
            
            $item['statusname'] = Manager::instance()->status[$item['status']];
            $item['group']  = !empty($auth_group[$item['group_id']]) ? $auth_group[$item['group_id']]['name'] : '';
            unset($item);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$data);
    }
    
    /**
     * 新增管理员
     * @param array $param
     * @return array
     */
    public function addManager(array $param):array
    {
        if (empty($param['mobile'])) {
            return Normal::returnCode(Normal::FAIL,"手机号必传");
        }
        $args = [
            'mobile'   => $param['mobile'],
        ];
        $checkMember = callTcpService('bbcUserAccountRegister',$args);
        if($checkMember['code']==200){
            $mid=$checkMember['data']['mid'];
        }else{
            return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
        }
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }
        if (empty($param['account'])) {
            return Normal::returnCode(Normal::FAIL,"账号必传");
        }
        $manager = Manager::instance()->info(['account' => $param['account']]);
        if (!empty($manager)) {
            return Normal::returnCode(Normal::FAIL,"账号已存在");
        }
        if (empty($param['password'])) {
            return Normal::returnCode(Normal::FAIL,"密码不能为空");
        }
        if (empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL,"名称不能为空");
        }
        if (empty($param['group_id'])) {
            return Normal::returnCode(Normal::FAIL,"请选择分组");
        }
        $data = [
            'account'   => $param['account'],
            'password'  => md5(trim($param['password'])),
            'name'      => $param['name'],
            'group_id'  => intval($param['group_id']),
            'mid'       => $mid,
            'cid'       => $param['cid'],
            'cb_id'     => $param['cb_id'],
            'cd'        => time(),
        ];
        $res = Manager::instance()->add($data);
        if($res){
            return Normal::returnCode(Normal::SUC,"新增成功");
        }else{
            return Normal::returnCode(Normal::FAIL,"新增失败");
        }
    }
    
    /**
     * 根据id获取管理员信息
     * @param array $param
     * @return array
     */
    public function getManagerById(array $param):array {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL,"id必传");
        }
        $where=[['id','=',$param['id']]];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }
        $manager= Manager::instance()->info($where);
        if(empty($manager)){
            return Normal::returnCode(Normal::FAIL,"未找到管理员信息");
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$manager); 
    }
    
    /**
     * 修改管理员
     * @param array $param
     * @return array
     */
    public function editManager(array $param):array
    {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL,"id必传");
        }
        $manager= Manager::instance()->info(['id'=>$param['id']]);
        if(empty($manager)){
            return Normal::returnCode(Normal::FAIL,"未找到管理员信息");
        }
        if (empty($param['account'])) {
            return Normal::returnCode(Normal::FAIL,"账号不能为空");
        }
            $where   = [
                ['account', '=', $param['account']],
                ['id', '<>', $param['id']],
            ];
            $managerrep = Manager::instance()->info($where);
            if (!empty($managerrep)) {
                return Normal::returnCode(Normal::FAIL,"账号已经存在");
            }
        if (empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL,"名称不能为空");
        }
        if (empty($param['group_id'])) {
            return Normal::returnCode(Normal::FAIL,"请选择分组");
        }else{
            $group= AuthGroup::instance()->info(['id'=>$param['group_id'],'cid'=>$manager['cid'],'cb_id'=>$manager['cb_id']]);
            if(empty($group)){
                return Normal::returnCode(Normal::FAIL,"group_id未找到相关分组");
            }
        }
        if (!isset($param['status']) && $param['status'] === '') {
            return Normal::returnCode(Normal::FAIL,"请选择状态");
            }
        $data = [
            'account'   => $param['account'],
            'name'      => $param['name'],
            'status'    => intval($param['status']),
            'group_id'  => intval($param['group_id']),
            'md'        => time(),
        ];
        if (!empty($param['password'])) {
            $data['password'] = md5(trim($param['password']));
        }
        $res = Manager::instance()->edit(['id' => $param['id']], $data);
        if (!$res) {
            return Normal::returnCode(Normal::FAIL,"修改失败");
        }
        return Normal::returnCode(Normal::SUC,"修改成功"); 
    }
    /**
     * 修改密码
     * @param array $param
     * @return array
     */
    public function editPass(array $param):array {
        $manager = Manager::instance()->info(['id'=>$param['manager_id']]);
        if (empty($param['password'])) {
            return Normal::returnCode(Normal::FAIL,"请输入密码");
        }
        if (empty($param['confirm_password'])) {
            return Normal::returnCode(Normal::FAIL,"请输入确认密码");
        }
        if ($param['password'] != $param['confirm_password']  ) {
            return Normal::returnCode(Normal::FAIL,"两次输入的密码不一样");
        }
        if (md5(trim($param['old_password'])) != $manager['password']  ) {
            return Normal::returnCode(Normal::FAIL,"旧密码错误");
        }
        $data['password'] = md5(trim($param['password']));
        $data['md']=time();
        $res = Manager::instance()->edit(['id' => $manager['id']], $data);
        if (!$res) {
            return Normal::returnCode(Normal::FAIL,"修改失败");
        }
        $this->userLogout($param);
        return Normal::returnCode(Normal::SUC,"修改成功");
    }
    
    /**
     * 获取权限组不分页
     * @param array $param
     * @return array
     */
    public function getAuthGropList(array $param):array {
        $where=[];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }else{
            $where[] = ['cb_id', '=', 0];
        }
        if (!empty($param['name'])) {
            $where[] = ['name', 'like', '%'.$param['name'].'%'];
        }
        if (!empty($param['cd_start'])) {
            $where[] = ['cd', '>=', strtotime($param['cd_start'])];
        }
        if (!empty($param['cd_end'])) {
            $where[] = ['cd', '<=', strtotime($param['cd_end'])];
        }
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['status', '=', $param['status']];
        }
        $data= AuthGroup::instance()->lists($where);
        foreach ($data as &$item) {
            $item['node']= $item['node']?explode(',', $item['node']):[];
            foreach($item['node'] as &$itemnode){
                $itemnode=(int)$itemnode;
                unset($itemnode);
            }
            $item['status_name']= AuthGroup::instance()->status[$item['status']];
            unset($item);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$data);
    }
    
    /**
     * 获取权限组要分页
     * @param array $param
     * @return array
     */
    public function getAuthGroupListByPage(array $param):array {        
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:20;
        $where=[];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }else{
            $where[] = ['cb_id', '=', 0];
        }
        if (!empty($param['name'])) {
            $where[] = ['name', 'like', '%'.$param['name'].'%'];
        }
        if (!empty($param['cd_start'])) {
            $where[] = ['cd', '>=', strtotime($param['cd_start'])];
        }
        if (!empty($param['cd_end'])) {
            $where[] = ['cd', '<=', strtotime($param['cd_end'])];
        }
        if(isset($param['status']) && $param['status'] !==''){
            $where[] = ['status', '=', $param['status']];
        }
        $data= AuthGroup::instance()->listPages($where, $limit, $page);
        foreach ($data as &$item) {
            $item['node']= $item['node']?explode(',', $item['node']):[];
            foreach($item['node'] as &$itemnode){
                $itemnode=(int)$itemnode;
                unset($itemnode);
            }
            $item['status_name']= AuthGroup::instance()->status[$item['status']];
            unset($item);
        }
        $count=AuthGroup::instance()->countNum($where);
        return Normal::returnCode(Normal::SUC,"获取成功",['list'=>$data,'total'=>$count]);
    }
    
    /**
     * 新增权限组
     * @param array $param
     * @return array
     */
    public function addAuthGroup(array $param):array {
        if (empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL,"名称不能为空");
        }
        $where=[['name','=',$param['name']]];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
            $cid=$param['cid'];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
            $cb_id=$param['cb_id'];
        }
        $group= AuthGroup::instance()->info($where);
        if (!empty($group)) {
            return Normal::returnCode(Normal::FAIL,"角色名已经存在");
        }
        if( !is_array($param['node'])){
            return Normal::returnCode(Normal::FAIL,"node 数据错误");
        }
        $auth_node = '';
        if (!empty($param['node'])) {
            $auth_node = implode(',', $param['node']);
        }
        $data = [
            'name' => $param['name'],
            'node' => $auth_node,
            'cb_id'=> $cb_id??0,
            'cid'  => $cid,
            'cd'   => time(),
        ];
        $res = AuthGroup::instance()->add($data);
        if (empty($res)) {
            return Normal::returnCode(Normal::FAIL,"新增失败");
        }else{
            return Normal::returnCode(Normal::SUC,"新增成功");
        }
    }
    
    /**
     * 修改权限组
     * @param array $param
     * @return array
     */
    public function editAuthGroup(array $param):array {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL,"id必传");
        }
        $group= AuthGroup::instance()->info(['id'=>$param['id']]);
        if (empty($group)) {
            return Normal::returnCode(Normal::FAIL,"未找到相关组信息");
        }
        if (empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL,"名称不能为空");
        }
        $where=[['name','=',$param['name']],['id','<>',$param['id']]];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
            $cid=$param['cid'];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
            $cb_id=$param['cb_id'];
        }
        $grouprep= AuthGroup::instance()->info($where);
        if (!empty($grouprep)) {
            return Normal::returnCode(Normal::FAIL,"角色名已经存在");
        }
        if(!is_array($param['node'])){
            return Normal::returnCode(Normal::FAIL,"node 数据错误");
        }
        $auth_node = '';
        if (!empty($param['node'])) {
            $auth_node = implode(',', $param['node']);
        }

        $data = [
            'name' => $param['name'],
            'status' => $param['status'],
            'node' => $auth_node,
            'cb_id'=> $cb_id??0,
            'cid'  => $cid,
            'cd'   => time(),
        ];
        if(isset($param['status']) && $param['status'] !==''){
            $data['status']=$param['status'];
        }
        $res = AuthGroup::instance()->edit(['id'=>$param['id']],$data);
        if (empty($res)) {
            return Normal::returnCode(Normal::FAIL,"修改失败");
        }else{
            return Normal::returnCode(Normal::SUC,"修改成功");
        }
    }
    
    /**
     * 根据id获取权限组信息
     * @param array $param
     * @return array
     */
    public function getAuthGroupById(array $param):array {
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL,"id必传");
        }
        $where=[['id','=',$param['id']]];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }
        $group= AuthGroup::instance()->info($where);
        if(empty($group)){
            return Normal::returnCode(Normal::FAIL,"未找到权限组信息");
        }
        $group['node']=$group['node']? explode(',', $group['node']):[];
        foreach($group['node'] as &$item){
            $item=(int)$item;
            unset($item);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$group); 
    }
    
    /**
     * 获取权限节点(树形)
     * @param array $param
     * @return array
     */
    public function getAuthNodeList(array $param):array {
        $where = [
            ['status','=',1],
            ['df','=',0],
            '_orderRaw_' => 'sort = 0, sort asc',
        ];
        if(!empty($param['cid'])){
            $where[] = ['type', 'in', [1,2]];
        }
        if(!empty($param['cb_id'])&&$param['cb_id']!=0){
            $where[] = ['type', 'in', [1,3]];
        }
        $auth_node = AuthNode::instance()->lists($where);
        $auth_node = tree($auth_node, 0, 'id', 'pid');
        return Normal::returnCode(Normal::SUC,"获取成功",$auth_node);
    }
    
    /**
     * 获取权限
     * @param array $param
     * @return array
     */
    public function getAuth(array $param):array {
        if (empty($param['group_id'])) {
            return Normal::returnCode(Normal::FAIL,"group_id必传");
        }
        $redis = getRedisObj();
        //获取超级管理员权限
        $where=[
            ['status','=',1],
            ['df','=',0]
        ];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $type = ['type', 'in', [1,2]];
            $root_auth_key = "ADMIN_ROOT_AUTH_CHANNEL";
        }
        if(!empty($param['cb_id'])&&$param['cb_id']!=0){
            $type = ['type', 'in', [1,3]];
            $root_auth_key = "ADMIN_ROOT_AUTH_CHANNEL_BUSINESS";
        }
        $where[]=$type;
        $admin_root_redis    = $redis->get($root_auth_key); 
        $admin_root= unserialize($admin_root_redis);
        if (empty($admin_root)) {            
            $admin_root = [];
            //获取所有权限节点
            $admin_root['all_node'] = AuthNode::instance()->lists($where);
            $where['_orderRaw_']= ' sort asc,sort = 0';
            $admin_root['root_auth'] = AuthNode::instance()->lists($where);
            $where[]   = ['is_menu','=',1];
            $admin_root['root_menu'] = AuthNode::instance()->lists($where);            
            $admin_root_redis= serialize($admin_root);
            $redis->set($root_auth_key, $admin_root_redis, 120);
        }
        $auth = $admin_root['root_auth'];
        $menu = $admin_root['root_menu'];        
        //权限组
        $group = AuthGroup::instance()->info(['id' => $param['group_id'], 'status' => 1]);
        if (empty($group)) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'menu'      => [],
                'auth'      => [],
                'front_auth'=> [],
                'all_node'  => array_column($admin_root['all_node'], 'node'),
            ]);
        }
        
        if ($group['is_root'] != 1) {//非超级管理员获取自己专有权限
            
            if (!empty($group['node'])) {
                $cache_key  = 'Admin_Auth_Data_Group_'.$group['id'];
                $admin_auth_redis = $redis->get($cache_key);
                $admin_auth= unserialize($admin_auth_redis);
                if (empty($admin_auth)) {//缓存为空,从库里获取
                    $admin_auth = [];
                    $where      = [
                        'status'  => 1,
                        'df'      => 0,
                        'id'      => explode(',', $group['node']),
                        '_orderRaw_' => 'sort = 0, sort asc',
                    ];
                    $admin_auth['auth'] = AuthNode::instance()->lists($where);
                    $where['is_menu']   = 1;
                    $admin_auth['menu'] = AuthNode::instance()->lists($where);
                    $admin_auth_redis= serialize($admin_auth);
                    $redis->set($cache_key, $admin_auth_redis, 120);
                }
                
                $auth = $admin_auth['auth'];
                $menu = $admin_auth['menu'];
            } else {
                return Normal::returnCode(Normal::SUC,"获取成功",[
                    'menu'      => [],
                    'auth'      => [],
                    'front_auth'=> [],
                    'all_node'  => array_column($admin_root['all_node'], 'node'),
                ]);
            }
        }
        
        $menu       = tree($menu, 0, 'id', 'pid');        
        $back_auth  = array_column($auth, 'node');
        $front_auth = array_column($auth, 'front_node');
        $all_node   = array_column($admin_root['all_node'], 'node');
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'menu'      => $menu,
            'auth'      => $back_auth,
            'front_auth'=> $front_auth,
            'all_node'  => $all_node,
        ]);
    }
    
    /**
     * 验证权限
     * @param array $param
     * @return array
     */
    public function checkAuth(array $param):array {
        if (empty($param['group_id'])) {
            return Normal::returnCode(Normal::FAIL,"group_id必传");
        }
        if (empty($param['path'])) {
            return Normal::returnCode(Normal::FAIL,"path必传");
        }
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }
        $res = $this->getAuth($param);              
        if (in_array($param['path'], $res['data']['all_node']) && !in_array($param['path'], $res['data']['auth'])) {
            return Normal::returnCode(Normal::NO_LOGIN,"该账号无权限访问");
        }
        return Normal::returnCode(Normal::SUC,"验证成功");
    }
    
    /**
     * 获取管理员日志
     * @param array $param
     * @return array
     */
    public function getManagerLogListByPage(array $param):array {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:20;
        $where=[];
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"cid 必传");
        }else{
            $where[] = ['cid', '=', $param['cid']];
        }
        if(!empty($param['cb_id'])){
            $where[] = ['cb_id', '=', $param['cb_id']];
        }else{
            $where[] = ['cb_id', '=', 0];
        }
//        if(!empty($param['manager_id'])){
//            $where[] = ['manager_id', '=', $param['manager_id']];
//        }
        if (!empty($param['content'])) {
            $where[] = ['content', 'like', '%'.$param['content'].'%'];
        }
        if (!empty($param['cd_start'])) {
            $where[] = ['cd', '>=', strtotime($param['cd_start'])];
        }
        if (!empty($param['cd_end'])) {
            $where[] = ['cd', '<=', strtotime($param['cd_end'])];
        }
        $where['_order_']='id desc';
        $data= ManagerLog::instance()->listPages($where, $limit, $page);
        $count=ManagerLog::instance()->countNum($where);
        return Normal::returnCode(Normal::SUC,"获取成功",['list'=>$data,'total'=>$count]);
    }
}
